var express = require('express');
var app = express();

// start socket listen
var ltcs_client = require('./ltcs_client.js');
ltcs_client.startListen();

// get: all online device
app.get('/devices/online', function(req, res) {
	var array = ltcs_client.getAllOnline();
	res.send(JSON.stringify(array));
});

// send msg to one device
app.post('/device/wakeup', function(req, res) {
	var data = '';
	req.on('data', function(chunk) {
		data += chunk;
	});
	// data may be string, like 'aabbcc' or Array '["aabbcc","xxyyzz"]'
	req.on('end', function() {
		res.writeHead(200, {
			'Content-type': 'text/plain'
		});
		res.end('ok\n');

		data = preProcess(data);
		ltcs_client.wakeup(data);
	});

	function preProcess(data) {
		// remove '"' in head or tail

		if (0 === data.indexOf('"') && data.length - 1 === data.lastIndexOf('"')) {
			console.log('data wrap by ""');
			data = data.substring(1, data.length - 1);
		}

		// check if Array
		var arr;
		try {
			arr = JSON.parse(data);
			return arr;
		} catch (e) {
			console.log('data not array');
		}

		return data;
	}
});

// error
app.use('/', function(req, res) {
	console.log('error: undefined path or method');
	res.end('error: undefined path or method');
})

app.listen(8080);
console.log('express start at 8080');